import json
import os
import socket
import threading
from psi.cmdLet import cmdLet
from conf import conf
receiver_port = 8080
with open(os.path.dirname(os.path.abspath(__file__)).replace("\\", "/") + "/../" + "conf/config.json", "r") as f:
    config = json.load(f)
    if "port" in config:
        receiver_port = config["port"]

def start_receiver():
    s = socket.socket()
    s.bind(('0.0.0.0', receiver_port))
    s.listen(5)  # 允许最多5个客户端连接
    print("服务器启动，等待连接")
    # 获取当前脚本所在目录的绝对路径
    base_dir = os.path.dirname(os.path.abspath(__file__)).replace("\\", "/")+"/../"
    while True:
        conn, addr = s.accept()
        # print(f"收到来自 {addr} 的连接")
        # 先接收 32 字节的模式选择
        mode =  conn.recv(32).strip().decode()
        if mode == "file":
            # 先接收 32 字节的对象名
            to = conn.recv(32).strip().decode()

            # 先接收 128 字节的文件名
            filename = conn.recv(128).strip().decode()
            # print(f"准备接收文件: {filename}")

            filename = base_dir + f"data/{to}/" + filename
            with open(filename, 'wb') as f:
                while True:
                    data = conn.recv(1024)
                    if not data:
                        break
                    f.write(data)
            # print(f"文件 {filename} 接收完毕")
        elif mode == "cmd":
            print("接收命令模式")
            # 接收 64 字节的命令
            cmd = conn.recv(64).strip().decode()
            cmdThreader = threading.Thread(target=cmdLet,args=(cmd,addr),daemon=True)
            cmdThreader.start()
        elif mode == "config":
            # 配置共享
            # 接收 32 字节的配置内容
            key = conn.recv(32).strip().decode()
            # 接收 64 字节的配置值
            value = conn.recv(64).strip().decode()
            value = int(value)
            conf.set_config(key, value)
            print(f"配置 {key} 已更新为 {value}")
        else:
            print("未知模式")
        conn.close()

if __name__ == "__main__":
    start_receiver()